<template>
  <div class="home">
    <hm-header class="home-header">
      <template #left>
        <i class="iconfont iconnew"></i>
      </template>
      <template #center>
        <div class="searchbox" @click="toSearch">
          <i class="iconfont iconsearch"></i>
          搜索新闻
        </div>
      </template>
      <template #right>
        <i class=" iconfont iconwode" @click="handleProfile"></i>
      </template>
    </hm-header>

      <van-tabs sticky
                background="#e4e4e4"
                swipe-threshold="6"
                swipeable
                @scroll="handleTabsScroll"
                @change="handleTabsClick"
                v-model="activeName">
        <!-- 导航标题 -->
        <van-tab v-for="(item) in categoryList" :key="item.id" :title="item.name" :name="item.id">
          <!-- 文章内容主体 -->
          <div v-if="articleList.length">
            <!-- 下拉刷新 -->
            <van-pull-refresh v-model="item.refreshing" @refresh="onRefresh">
              <!-- 上拉加载更多 -->
              <van-list
                v-model="item.loading"
                :finished="item.finished"
                finished-text="没有更多了"
                @load="onLoad"
              >
                <!-- 文章item -->
                <hm-post-item v-for="artItem in articleList"
                              :key="artItem.id"
                              :artItem="artItem">
                </hm-post-item>
              </van-list>
            </van-pull-refresh>
          </div>
          <!-- 分类无内容占位 -->
          <div class="no-content" v-if="isNoContent">该分类暂时没有文章哦</div>
        </van-tab>
        <van-tab disabled></van-tab>
        <!-- 下拉箭头 -->
        <div class="add-btn" :class="{'add-btn-fixed': isAddFixed}" @click="toColumnAdminister">
          <i class="iconfont iconjiantou1"></i>
        </div>
      </van-tabs>
  </div>
</template>

<script>
import HmPostItem from 'components/hm-post-item.vue'
export default {
  name: 'Home',
  data () {
    return {
      activeName: 999,
      categoryList: [],
      articleList: [],
      isAddFixed: false,
      pageSize: 5,
      isNoContent: false
    }
  },

  components: {
    HmPostItem
  },

  async created () {
    const colunmList = JSON.parse(localStorage.getItem('categoryList'))
    if (colunmList) {
      colunmList.forEach(v => {
        v.pageIndex = 0
        v.loading = false
        v.finished = false
        v.refreshing = false
      })
      this.categoryList = colunmList
    } else {
      await this.getCategoryList()
    }
    this.getArticleList(999)
  },

  methods: {
    // 获取分类列表
    async getCategoryList () {
      const { data: res } = await this.$axios.get('/category')
      const { statusCode, data } = res
      if (statusCode !== 200) {
        return this.$toast.fail('获取分类列表失败')
      }
      const dataTop = data.filter(v => v.is_top === 1)
      dataTop.forEach(v => {
        v.pageIndex = 0
        v.loading = false
        v.finished = false
        v.refreshing = false
      })
      this.categoryList = dataTop
    },

    // 获取文章列表
    async getArticleList (categoryId) {
      const currentCategory = this.categoryList.filter(v => v.id === categoryId)[0]
      const { data: res } = await this.$axios.get('/post',
        {
          params: {
            category: categoryId,
            pageIndex: currentCategory.pageIndex + 1,
            pageSize: this.pageSize
          }
        })
      this.categoryList.filter(v => v.id === categoryId)[0].loading = false

      const { statusCode, data } = res
      if (statusCode !== 200) {
        return this.$toast.fail('获取文章列表失败')
      }
      // 加载完全部改变finished状态
      if (data.length < this.pageSize) {
        this.categoryList.filter(v => v.id === categoryId)[0].finished = true
      }
      // 数据缓存
      this.categoryList.filter(v => v.id === categoryId)[0].pageIndex++
      this.articleList = this.categoryList.filter(v => v.id === categoryId)[0].articleList = [...currentCategory.articleList || [], ...data]
      this.isNoContent = !this.articleList.length
    },

    // 处理tab滚动事件
    handleTabsScroll (scrollObj) {
      this.isAddFixed = scrollObj.isFixed
    },

    // 处理tab点击事件
    handleTabsClick (name, title) {
      this.articleList = []
      // 判断是否有缓存数据
      const isCacheCurrent = this.categoryList.filter(v => {
        return v.id === name
      })[0].articleList || []
      if (isCacheCurrent.length) {
        this.articleList = isCacheCurrent
        return false
      }
      this.getArticleList(name)
    },

    // 上拉加载更多
    onLoad () {
      this.getArticleList(this.activeName)
    },

    // 下拉刷新
    async onRefresh () {
      this.articleList = []
      this.categoryList.filter(v => v.id === this.activeName)[0].pageIndex = 0
      this.categoryList.filter(v => v.id === this.activeName)[0].loading = false
      this.categoryList.filter(v => v.id === this.activeName)[0].finished = false
      this.categoryList.filter(v => v.id === this.activeName)[0].articleList = []

      await this.getArticleList(this.activeName)
      this.$toast('刷新成功')
      this.categoryList.filter(v => v.id === this.activeName)[0].finished = false
    },

    // 我的
    handleProfile () {
      this.$router.push('/profile').catch(err => err)
    },

    // 去搜索页
    toSearch () {
      this.$router.push('/search')
    },

    // 去栏目管理
    toColumnAdminister () {
      this.$router.push('/columnAdminister').catch(err => err)
    }
  },

  watch: {
    $route (to, from) {
      console.log(from)
      if (from.path === '/columnAdminister') {
        this.$router.go(0)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.home {
  .home-header {
    background-color: #eb3323;
    color: #fff;
    .iconnew {
      display: block;
      width: 50px;
      height: 50px;
      font-size: 50px;
    }
    .searchbox {
      margin-left: 10px;
      height: 34px;
      line-height: 34px;
      background-color: #ef938b;
      color: #fff;
      border-radius: 17px;
      font-weight: normal;
    }
    .iconwode {
      display: block;
      width: 50px;
      height: 50px;
      font-size: 22px;
    }
  }

  .van-tabs {
    .add-btn {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 9;
      width: 14.667%;
      height: 44px;
      line-height: 44px;
      background-color: #e4e4e4;
      text-align: center;

      &.add-btn-fixed {
        position: fixed;
        z-index: 99;
      }

      .iconjiantou1:before {
        display: inline-block;
        transform: rotate(90deg);
      }
    }

    .no-content {
      padding: 100px;
      text-align: center;
      font-size: 14px;
    }
  }

}

</style>
